<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Python," />




  


  <link rel="alternate" href="/atom.xml" title="Richey's Blog" type="application/atom+xml" />






<meta name="description" content="数据类型和数据结构基础数据类型 整数 int 123 浮点数 float 1.234 字符串 str “Python” 布尔值 bool True False  123456789&gt;&gt;&gt; type(123)&lt;class &#39;int&#39;&gt;&gt;&gt;&gt; type(&quot;Phthon&quot;)&lt;class &#39;str&#39;&amp;">
<meta property="og:type" content="article">
<meta property="og:title" content="python基础">
<meta property="og:url" content="http://10000hours.top/2021/01/30/python%E5%9F%BA%E7%A1%80/index.html">
<meta property="og:site_name" content="Richey&#39;s Blog">
<meta property="og:description" content="数据类型和数据结构基础数据类型 整数 int 123 浮点数 float 1.234 字符串 str “Python” 布尔值 bool True False  123456789&gt;&gt;&gt; type(123)&lt;class &#39;int&#39;&gt;&gt;&gt;&gt; type(&quot;Phthon&quot;)&lt;class &#39;str&#39;&amp;">
<meta property="article:published_time" content="2021-01-29T16:00:00.000Z">
<meta property="article:modified_time" content="2021-01-30T17:01:36.004Z">
<meta property="article:author" content="Richey Liu">
<meta property="article:tag" content="Python">
<meta name="twitter:card" content="summary">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://10000hours.top/2021/01/30/python基础/"/>





  <title>python基础 | Richey's Blog</title>
  








<meta name="generator" content="Hexo 4.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Richey's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">吾生也有涯，而知也无涯。以有涯随无涯，殆已。</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://10000hours.top/2021/01/30/python%E5%9F%BA%E7%A1%80/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Richey Liu">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Richey's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">python基础</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2021-01-30T00:00:00+08:00">
                2021-01-30
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Phthon/" itemprop="url" rel="index">
                    <span itemprop="name">Phthon</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2021/01/30/python%E5%9F%BA%E7%A1%80/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2021/01/30/python%E5%9F%BA%E7%A1%80/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/2021/01/30/python%E5%9F%BA%E7%A1%80/" class="leancloud_visitors" data-flag-title="python基础">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="数据类型和数据结构"><a href="#数据类型和数据结构" class="headerlink" title="数据类型和数据结构"></a>数据类型和数据结构</h1><h2 id="基础数据类型"><a href="#基础数据类型" class="headerlink" title="基础数据类型"></a>基础数据类型</h2><ol>
<li>整数 int 123</li>
<li>浮点数 float 1.234</li>
<li>字符串 str “Python”</li>
<li>布尔值 bool True False</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; type(123)</span><br><span class="line">&lt;class &#39;int&#39;&gt;</span><br><span class="line">&gt;&gt;&gt; type(&quot;Phthon&quot;)</span><br><span class="line">&lt;class &#39;str&#39;&gt;</span><br><span class="line">&gt;&gt;&gt; type(1.234)</span><br><span class="line">&lt;class &#39;float&#39;&gt;</span><br><span class="line">&gt;&gt;&gt; type(True)</span><br><span class="line">&lt;class &#39;bool&#39;&gt;</span><br><span class="line">&gt;&gt;&gt;</span><br></pre></td></tr></table></figure>

<p>类型转换</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>int(<span class="string">'123'</span>)</span><br><span class="line"><span class="number">123</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>str(<span class="number">123</span>)</span><br><span class="line"><span class="string">'123'</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>bool(<span class="number">123</span>)</span><br><span class="line"><span class="literal">True</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>bool(<span class="number">0</span>)</span><br><span class="line"><span class="literal">False</span></span><br></pre></td></tr></table></figure>


<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"># 计算薪资</span><br><span class="line"># 工作天数</span><br><span class="line">workday &#x3D; 21.75;</span><br><span class="line"># 日薪</span><br><span class="line">dailyPay &#x3D; 288;</span><br><span class="line"># 奖金</span><br><span class="line">bonus &#x3D; 566;</span><br><span class="line">total &#x3D; workday * dailyPay + bonus;</span><br><span class="line">print(total);</span><br></pre></td></tr></table></figure>

<h2 id="序列"><a href="#序列" class="headerlink" title="序列"></a>序列</h2><p>序列有两个特性</p>
<ol>
<li>成员是有序的</li>
<li>可以通过下标访问一个或几个成员</li>
</ol>
<ul>
<li>字符串、列表、元组都属于序列</li>
</ul>
<ol>
<li>字符串 “春夏秋冬”</li>
<li>列表 [1,”春”,2,”秋”]</li>
<li>元组 (“春”,”夏”,”秋”,”冬”)  元组中存放不可变更的内容,没有增加删除等功能</li>
</ol>
<ul>
<li>序列基本操作</li>
</ul>
<ol>
<li>[not] in 成员关系</li>
<li><ul>
<li>连接 </li>
</ul>
</li>
<li><ul>
<li>重复</li>
</ul>
</li>
<li>: 切片 </li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"># 数据结构相关</span><br><span class="line"># 四季</span><br><span class="line">seasons &#x3D; [&quot;春&quot;, &quot;夏&quot;, &quot;秋&quot;, &quot;冬&quot;];</span><br><span class="line"></span><br><span class="line"># ---------------------切片操作</span><br><span class="line"># 第一季</span><br><span class="line">print(seasons[0])</span><br><span class="line"># 第一季和第三季</span><br><span class="line">print(seasons[0:2])</span><br><span class="line"># 倒数第一季</span><br><span class="line">print(seasons[-1])</span><br><span class="line"></span><br><span class="line"># ---------------------连接操作</span><br><span class="line">print(seasons + seasons)</span><br><span class="line">print(seasons + [1,2,3])</span><br><span class="line"></span><br><span class="line"># ---------------------重复操作</span><br><span class="line">print(seasons * 2)</span><br><span class="line"># ---------------------关系操作</span><br><span class="line">print(&quot;春&quot; in seasons)</span><br><span class="line">print(&quot;春&quot; not in seasons)</span><br><span class="line"></span><br><span class="line"># 结果</span><br><span class="line">春</span><br><span class="line">[&#39;春&#39;, &#39;夏&#39;]</span><br><span class="line">冬</span><br><span class="line">[&#39;春&#39;, &#39;夏&#39;, &#39;秋&#39;, &#39;冬&#39;, &#39;春&#39;, &#39;夏&#39;, &#39;秋&#39;, &#39;冬&#39;]</span><br><span class="line">[&#39;春&#39;, &#39;夏&#39;, &#39;秋&#39;, &#39;冬&#39;, 1, 2, 3]</span><br><span class="line">[&#39;春&#39;, &#39;夏&#39;, &#39;秋&#39;, &#39;冬&#39;, &#39;春&#39;, &#39;夏&#39;, &#39;秋&#39;, &#39;冬&#39;]</span><br><span class="line">True</span><br><span class="line">False</span><br></pre></td></tr></table></figure>
<p>元组demo 计算某一天属于哪个季节</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"># 计算某一天属于哪个季节</span><br><span class="line"></span><br><span class="line"># 计算某一天属于哪个季节</span><br><span class="line"></span><br><span class="line">seasons &#x3D; (&quot;春&quot;,&quot;夏&quot;,&quot;秋&quot;,&quot;冬&quot;)</span><br><span class="line"></span><br><span class="line"># 季节的第一天</span><br><span class="line">seasonsFirstDays &#x3D; ((1,1),(4,1),(7,1),(10,1))</span><br><span class="line"></span><br><span class="line">(month,day) &#x3D; (2,11)</span><br><span class="line">#(month,day) &#x3D; list(map(int,input(&quot;请输入月和日，用空格隔开&quot;).split()))</span><br><span class="line">print((month,day))</span><br><span class="line">filterSeasonFirstDay &#x3D; filter(lambda x : x &lt;&#x3D; (month,day),seasonsFirstDays)</span><br><span class="line">filterSeasonFirstDayLen  &#x3D; len(list(filterSeasonFirstDay))</span><br><span class="line">seasonIndex &#x3D; filterSeasonFirstDayLen % 4 -1</span><br><span class="line">print(seasonIndex)</span><br><span class="line">print(seasons[seasonIndex])</span><br><span class="line"></span><br><span class="line">[(1, 1)]</span><br><span class="line">-1</span><br><span class="line">冬</span><br></pre></td></tr></table></figure>

<p>列表demo </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"># 列表的操作，区别于元组，列表可以添加和删除</span><br><span class="line"></span><br><span class="line">bonusItem &#x3D; [&quot;全勤奖&quot;,&quot;绩效奖&quot;]</span><br><span class="line"></span><br><span class="line">bonusItem.append(&quot;项目奖&quot;)</span><br><span class="line">print(bonusItem)</span><br><span class="line">bonusItem.remove(&quot;绩效奖&quot;)</span><br><span class="line">print(bonusItem)</span><br><span class="line"></span><br><span class="line">[&#39;全勤奖&#39;, &#39;绩效奖&#39;, &#39;项目奖&#39;]</span><br><span class="line">[&#39;全勤奖&#39;, &#39;项目奖&#39;]</span><br></pre></td></tr></table></figure>
<h2 id="字典-key-value"><a href="#字典-key-value" class="headerlink" title="字典(key-value)"></a>字典(key-value)</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;&quot;basesalary&quot;:&quot;4000&quot;,&quot;bonux&quot;:&quot;1888&quot;&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"># 字典类型的使用</span><br><span class="line"></span><br><span class="line">dic1 &#x3D; &#123;&#125;</span><br><span class="line">print(type(dic1))</span><br><span class="line"></span><br><span class="line">dic2 &#x3D; &#123;&#39;basesalary&#39;:4000,&#39;bonus&#39;:1888&#125;</span><br><span class="line">dic2[&#39;postwage&#39;] &#x3D; 800</span><br><span class="line">print(dic2)</span><br><span class="line"></span><br><span class="line">&lt;class &#39;dict&#39;&gt;</span><br><span class="line">&#123;&#39;basesalary&#39;: 4000, &#39;bonus&#39;: 1888, &#39;postwage&#39;: 800&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"># 计算1到10所有偶数的平方</span><br><span class="line">list1 &#x3D; []</span><br><span class="line">for i in range(1,11):</span><br><span class="line">    if(i % 2 &#x3D;&#x3D; 0):</span><br><span class="line">        list1.append(i * i)</span><br><span class="line"></span><br><span class="line">print(list1)</span><br><span class="line"></span><br><span class="line"># 列表推导式语法</span><br><span class="line">list2 &#x3D; [i * i for i in range(1,11) if i % 2 &#x3D;&#x3D; 0]</span><br><span class="line">print(list2)</span><br><span class="line"></span><br><span class="line">upNumber &#x3D; (&quot;壹&quot;,&quot;贰&quot;,&quot;叁&quot;,&quot;肆&quot;,&quot;伍&quot;,&quot;陆&quot;,&quot;柒&quot;,&quot;捌&quot;,&quot;玖&quot;,&quot;拾&quot;)</span><br><span class="line">dic1 &#x3D; &#123;&#125;</span><br><span class="line">for i in upNumber:</span><br><span class="line">    dic1[i] &#x3D; 0;</span><br><span class="line">print(dic1)</span><br><span class="line"># 字典推导式语法</span><br><span class="line">dic2 &#x3D; &#123;i:0 for i in upNumber&#125;</span><br><span class="line">print(dic2)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">[4, 16, 36, 64, 100]</span><br><span class="line">[4, 16, 36, 64, 100]</span><br><span class="line">&#123;&#39;壹&#39;: 0, &#39;贰&#39;: 0, &#39;叁&#39;: 0, &#39;肆&#39;: 0, &#39;伍&#39;: 0, &#39;陆&#39;: 0, &#39;柒&#39;: 0, &#39;捌&#39;: 0, &#39;玖&#39;: 0, &#39;拾&#39;: 0&#125;</span><br><span class="line">&#123;&#39;壹&#39;: 0, &#39;贰&#39;: 0, &#39;叁&#39;: 0, &#39;肆&#39;: 0, &#39;伍&#39;: 0, &#39;陆&#39;: 0, &#39;柒&#39;: 0, &#39;捌&#39;: 0, &#39;玖&#39;: 0, &#39;拾&#39;: 0&#125;</span><br></pre></td></tr></table></figure>

<h1 id="流程控制"><a href="#流程控制" class="headerlink" title="流程控制"></a>流程控制</h1><h2 id="if"><a href="#if" class="headerlink" title="if"></a>if</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">if 表达式:</span><br><span class="line">   代码块</span><br><span class="line">elif 表达式:</span><br><span class="line">   代码块</span><br><span class="line">else :</span><br><span class="line">  代码块</span><br></pre></td></tr></table></figure>
<h2 id="for"><a href="#for" class="headerlink" title="for"></a>for</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">for 迭代变量 in 可迭代对象:</span><br><span class="line">    代码块</span><br></pre></td></tr></table></figure>
<h2 id="while"><a href="#while" class="headerlink" title="while"></a>while</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">while 表达式:</span><br><span class="line">      代码块</span><br></pre></td></tr></table></figure>

<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">upNumber &#x3D; (&quot;壹&quot;,&quot;贰&quot;,&quot;叁&quot;,&quot;肆&quot;,&quot;伍&quot;,&quot;陆&quot;,&quot;柒&quot;,&quot;捌&quot;,&quot;玖&quot;,&quot;拾&quot;)</span><br><span class="line">for num in range(10):</span><br><span class="line">    print(&quot;%s 的大写方式是:%s&quot; %(num,upNumber[(num - 1) % 10]))</span><br><span class="line"></span><br><span class="line">for idx in upNumber:</span><br><span class="line">    print(idx)</span><br></pre></td></tr></table></figure>

<h1 id="文件操作"><a href="#文件操作" class="headerlink" title="文件操作"></a>文件操作</h1><p>基本操作</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"># 文件操作</span><br><span class="line"></span><br><span class="line"># w是覆盖写入模式</span><br><span class="line">salaryfieldFile &#x3D; open(&#39;salaryfield.txt&#39;,&#39;w&#39;)</span><br><span class="line">salaryfieldFile.write(&quot;基本工资&quot;)</span><br><span class="line">salaryfieldFile.close()</span><br><span class="line"></span><br><span class="line">fieldRead &#x3D; open(&#39;salaryfield.txt&#39;)</span><br><span class="line">print(fieldRead.read())</span><br><span class="line">fieldRead.close()</span><br><span class="line"></span><br><span class="line"># 追加写入模式 a</span><br><span class="line"></span><br><span class="line">fieldAppend &#x3D; open(&#39;salaryfield.txt&#39;,&#39;a&#39;)</span><br><span class="line">fieldAppend.write(&#39;岗位工资&#39;)</span><br><span class="line">fieldAppend.close()</span><br></pre></td></tr></table></figure>

<p>指针操作</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"># 文件指针操作</span><br><span class="line"></span><br><span class="line">file &#x3D; open(&quot;salaryfield.txt&quot;)</span><br><span class="line">print(&quot;当前文件指针位置%s：&quot;%file.tell())</span><br><span class="line">print(&quot;我们读取了一个字符：%s&quot;%file.read(1))</span><br><span class="line">print(&quot;当前文件指针位置%s：&quot;%file.tell())</span><br><span class="line">file.seek(0)</span><br><span class="line">print(&quot;进行指针移动操作&quot;)</span><br><span class="line">print(&quot;当前文件指针位置%s：&quot;%file.tell())</span><br><span class="line"># seek 函数第一个参数是偏移量，第二个参数是相对位置：0表示从文件开头 1表示从当前位置 2表示从文件结尾</span><br><span class="line">file.seek(5,0)</span><br><span class="line">file.close()</span><br><span class="line"></span><br><span class="line">当前文件指针位置0：</span><br><span class="line">我们读取了一个字符：基</span><br><span class="line">当前文件指针位置3：</span><br><span class="line">进行指针移动操作</span><br><span class="line">当前文件指针位置0：</span><br></pre></td></tr></table></figure>
<h1 id="异常处理"><a href="#异常处理" class="headerlink" title="异常处理"></a>异常处理</h1><p>异常处理语法</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">try:</span><br><span class="line">  代码块</span><br><span class="line">except Exception[,reason]</span><br><span class="line">  异常处理</span><br><span class="line">final:</span><br><span class="line">  最终执行代码</span><br></pre></td></tr></table></figure>

<p>异常处理demo</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"># 异常处理</span><br><span class="line">try:</span><br><span class="line"> i &#x3D; j</span><br><span class="line">except NameError:</span><br><span class="line">    print(&#39;变量未定义异常&#39;)</span><br><span class="line"></span><br><span class="line">try:</span><br><span class="line"> 1&#x2F;0</span><br><span class="line">except ZeroDivisionError:</span><br><span class="line">    print(&#39;除数不能为0&#39;)</span><br><span class="line"></span><br><span class="line"># 捕获多个异常</span><br><span class="line">try:</span><br><span class="line"> 1&#x2F;0</span><br><span class="line">except (NameError,ZeroDivisionError):</span><br><span class="line">    print(&#39;程序出现了异常&#39;)</span><br><span class="line"></span><br><span class="line"># 打印异常信息</span><br><span class="line">try:</span><br><span class="line"> 1&#x2F;0</span><br><span class="line">except ZeroDivisionError as e:</span><br><span class="line">    print(&#39;除数不能为0,%s&#39;%e)</span><br><span class="line"></span><br><span class="line"># 通用异常捕获</span><br><span class="line">try:</span><br><span class="line"> 1&#x2F;0</span><br><span class="line">except Exception as e:</span><br><span class="line">    print(&#39;程序异常,%s&#39;%e)</span><br><span class="line"></span><br><span class="line"># 自定义异常信息</span><br><span class="line">try:</span><br><span class="line"> raise NameError(&quot;这个一个自定义的异常信息&quot;)</span><br><span class="line">except Exception as e:</span><br><span class="line">    print(&#39;程序异常,%s&#39;%e)</span><br><span class="line"></span><br><span class="line"># final执行操作</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">try:</span><br><span class="line">  file &#x3D; open(&quot;salaryfield.txt&quot;)</span><br><span class="line">except Exception as e:</span><br><span class="line">    print(&#39;文件操作异常%s&#39;%e)</span><br><span class="line">finally:</span><br><span class="line">    file.close()</span><br><span class="line">    print(&quot;文件关闭&quot;)</span><br></pre></td></tr></table></figure>

<h1 id="函数"><a href="#函数" class="headerlink" title="函数"></a>函数</h1><h2 id="函数定义"><a href="#函数定义" class="headerlink" title="函数定义"></a>函数定义</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">def functionName(param1,param2,*other,**keywords):</span><br><span class="line">    代码</span><br><span class="line">    return 需要返回的内容</span><br><span class="line"></span><br><span class="line">参数分为3种</span><br><span class="line"></span><br><span class="line">param1,param2属属于必填的普通参数</span><br><span class="line">*other 是可变长参数，可以是0个或者一个</span><br><span class="line">**keywords 是关键字参数，可以通过调用的时候指定参数</span><br></pre></td></tr></table></figure>
<h2 id="函数变量作用域"><a href="#函数变量作用域" class="headerlink" title="函数变量作用域"></a>函数变量作用域</h2><p>默认函数内定义的变量，作用域只能在函数内</p>
<p>global关键字可以改变函数作用域为全局</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line">## 函数作用域</span><br><span class="line"></span><br><span class="line">var &#x3D; 123</span><br><span class="line">def func1():</span><br><span class="line">    var &#x3D; 456</span><br><span class="line">    print(var)</span><br><span class="line"></span><br><span class="line">func1()</span><br><span class="line">print(var)</span><br><span class="line"></span><br><span class="line">global var2</span><br><span class="line">var2 &#x3D; 123</span><br><span class="line">def func2():</span><br><span class="line">    var2 &#x3D; 456</span><br><span class="line">    print(var2)</span><br><span class="line"></span><br><span class="line">func2()</span><br><span class="line">print(var2)</span><br><span class="line"></span><br><span class="line">var3 &#x3D; 123</span><br><span class="line">def func3():</span><br><span class="line">    global var3;</span><br><span class="line">    var3 &#x3D; 456</span><br><span class="line">    print(var3)</span><br><span class="line"></span><br><span class="line">func3()</span><br><span class="line">print(var3)</span><br><span class="line"></span><br><span class="line">456</span><br><span class="line">123</span><br><span class="line">456</span><br><span class="line">123</span><br><span class="line">456</span><br><span class="line">456</span><br></pre></td></tr></table></figure>

<h2 id="函数迭代器和生成器"><a href="#函数迭代器和生成器" class="headerlink" title="函数迭代器和生成器"></a>函数迭代器和生成器</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"># 生成器（通过yield实现迭代器功能）</span><br><span class="line">def floatRange(start,stop,step):</span><br><span class="line">    x &#x3D; start</span><br><span class="line">    while x &lt; stop:</span><br><span class="line">        yield x #迭代x</span><br><span class="line">        x +&#x3D; step</span><br><span class="line"></span><br><span class="line">for i in floatRange(10,20,0.5):</span><br><span class="line">    print(i)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">10</span><br><span class="line">10.5</span><br><span class="line">11.0</span><br><span class="line">11.5</span><br><span class="line">12.0</span><br><span class="line">12.5</span><br><span class="line">13.0</span><br><span class="line">13.5</span><br><span class="line">14.0</span><br><span class="line">14.5</span><br><span class="line">15.0</span><br><span class="line">15.5</span><br><span class="line">16.0</span><br><span class="line">16.5</span><br><span class="line">17.0</span><br><span class="line">17.5</span><br><span class="line">18.0</span><br><span class="line">18.5</span><br><span class="line">19.0</span><br><span class="line">19.5</span><br></pre></td></tr></table></figure>

<h2 id="lambda表达式"><a href="#lambda表达式" class="headerlink" title="lambda表达式"></a>lambda表达式</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"># lambda表达式</span><br><span class="line"></span><br><span class="line">&gt;&gt;&gt; def add(x,y):</span><br><span class="line">...     return x+y</span><br><span class="line">... </span><br><span class="line">&gt;&gt;&gt; add(3,5)</span><br><span class="line">8</span><br><span class="line">&gt;&gt;&gt; lambda x,y:x+y</span><br><span class="line">&lt;function &lt;lambda&gt; at 0x7f0b8d3fcb00&gt;</span><br><span class="line">&gt;&gt;&gt;</span><br></pre></td></tr></table></figure>

<h2 id="内建函数"><a href="#内建函数" class="headerlink" title="内建函数"></a>内建函数</h2><p>filter、map、reduce、zip</p>
<p>help 函数名可以产看帮助文档</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"># filter函数 过滤</span><br><span class="line"></span><br><span class="line">&gt;&gt; list2 &#x3D; [1,2,3,4,5,6,7]</span><br><span class="line">&gt;&gt;&gt; print(list(filter(lambda x:x&lt;4,list2)))</span><br><span class="line">[1, 2, 3]</span><br><span class="line"></span><br><span class="line"># map函数 对内容依次处理</span><br><span class="line"></span><br><span class="line">&gt;&gt;&gt; a &#x3D; [1,2,3,4,5,6,7]</span><br><span class="line">&gt;&gt;&gt; print(list(map(lambda x:x+1,a)))</span><br><span class="line">[2, 3, 4, 5, 6, 7, 8]</span><br><span class="line">&gt;&gt;&gt; b &#x3D; [1,2,3,4,5,6,7]</span><br><span class="line">&gt;&gt;&gt; print(list(map(lambda x,y:x+y,a,b)))</span><br><span class="line">[2, 4, 6, 8, 10, 12, 14]</span><br><span class="line"></span><br><span class="line"># reduce函数 </span><br><span class="line">[2, 4, 6, 8, 10, 12, 14]</span><br><span class="line">&gt;&gt;&gt; from functools import reduce</span><br><span class="line">&gt;&gt;&gt; reduce(lambda x,y:x+y,[1,2,3],1)</span><br><span class="line">7</span><br><span class="line">等价于 ((1+1)+2)+3</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"># zip函数 常用于合并累加等</span><br><span class="line"></span><br><span class="line">&gt;&gt;&gt; zip((1,2,3),(4,5,6))</span><br><span class="line">&lt;zip object at 0x7f0b8d3e3c30&gt;</span><br><span class="line">&gt;&gt;&gt; for i in zip((1,2,3),(4,5,6)):</span><br><span class="line">...    print(i)</span><br><span class="line">...</span><br><span class="line">(1, 4)</span><br><span class="line">(2, 5)</span><br><span class="line">(3, 6)</span><br><span class="line"></span><br><span class="line">#通过zip实现字段key-value对调</span><br><span class="line"></span><br><span class="line">&gt;&gt;&gt; dicta &#x3D; &#123;&quot;a&quot;:&quot;aa&quot;,&quot;b&quot;:&quot;bb&quot;&#125;</span><br><span class="line">&gt;&gt;&gt; zip(dicta.values(),dicta.keys())</span><br><span class="line">&lt;zip object at 0x7f0b8d302780&gt;</span><br><span class="line">&gt;&gt;&gt; print(dict(zip(dicta.values(),dicta.keys())))</span><br><span class="line">&#123;&#39;aa&#39;: &#39;a&#39;, &#39;bb&#39;: &#39;b&#39;&#125;</span><br></pre></td></tr></table></figure>

<h2 id="闭包"><a href="#闭包" class="headerlink" title="闭包"></a>闭包</h2><p>外部函数变量被内部函数引用，这种形式称之为闭包</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"># 闭包</span><br><span class="line"></span><br><span class="line"># 计数器</span><br><span class="line">def counter(FIRST&#x3D;0):</span><br><span class="line">    cnt &#x3D; [FIRST]</span><br><span class="line">    def addOne():</span><br><span class="line">        cnt[0] +&#x3D; 1</span><br><span class="line">        return cnt[0]</span><br><span class="line">    return addOne</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">num1 &#x3D; counter()</span><br><span class="line">num5 &#x3D; counter(5)</span><br><span class="line"></span><br><span class="line">print(num1())</span><br><span class="line">print(num1())</span><br><span class="line">print(num1())</span><br><span class="line">print(num5())</span><br><span class="line">print(num5())</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td></tr></table></figure>

<h2 id="装饰器"><a href="#装饰器" class="headerlink" title="装饰器"></a>装饰器</h2><p>装饰器用来装饰函数，通过闭包实现。有点java aop的意思</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"># 装饰器的使用</span><br><span class="line"></span><br><span class="line"># 通过闭包实现的装饰器</span><br><span class="line">def wash(func):</span><br><span class="line">    def wrapper(food):</span><br><span class="line">        print(&quot;吃饭前先洗手...&quot;)</span><br><span class="line">        print(&quot;函数调用名%s&quot;%func.__name__)</span><br><span class="line">        func(food)</span><br><span class="line">        print(&quot;吃完饭要漱口...&quot;)</span><br><span class="line"></span><br><span class="line">    return wrapper</span><br><span class="line"></span><br><span class="line">def newWash(args):</span><br><span class="line">    def wash(func):</span><br><span class="line">        def wrapper(food):</span><br><span class="line">            print(&quot;%s前先洗手...&quot;%args)</span><br><span class="line">            func(food)</span><br><span class="line">            print(&quot;吃完%s要漱口...&quot;%args)</span><br><span class="line"></span><br><span class="line">        return wrapper</span><br><span class="line">    return wash;</span><br><span class="line"></span><br><span class="line">def eat():</span><br><span class="line">    print(&quot;开始吃饭&quot;)</span><br><span class="line"></span><br><span class="line"># 没使用装饰器前</span><br><span class="line">print(&quot;吃饭前先洗手...&quot;)</span><br><span class="line">eat()</span><br><span class="line">print(&quot;吃完饭要漱口...&quot;)</span><br><span class="line"></span><br><span class="line">@wash</span><br><span class="line">def eat2(food):</span><br><span class="line">    print(&quot;开始吃%s&quot;%food)</span><br><span class="line"></span><br><span class="line">eat2(&quot;面包&quot;)</span><br><span class="line"></span><br><span class="line">@newWash(&quot;早饭&quot;)</span><br><span class="line">def eat3(food):</span><br><span class="line">    print(&quot;开始吃%s&quot;%food)</span><br><span class="line"></span><br><span class="line">eat3(&quot;烤肉&quot;)</span><br><span class="line"></span><br><span class="line">吃饭前先洗手...</span><br><span class="line">开始吃饭</span><br><span class="line">吃完饭要漱口...</span><br><span class="line">吃饭前先洗手...</span><br><span class="line">开始吃面包</span><br><span class="line">吃完饭要漱口...</span><br><span class="line">早饭前先洗手...</span><br><span class="line">开始吃烤肉</span><br><span class="line">吃完早饭要漱口...</span><br></pre></td></tr></table></figure>

<h2 id="上下文管理器with"><a href="#上下文管理器with" class="headerlink" title="上下文管理器with"></a>上下文管理器with</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"># 上下文管理器 with</span><br><span class="line"></span><br><span class="line">try:</span><br><span class="line">    file &#x3D; open(&quot;salaryfield.txt&quot;)</span><br><span class="line">    for line in file.readlines():</span><br><span class="line">        print(line)</span><br><span class="line">except Exception as e:</span><br><span class="line">    print(e)</span><br><span class="line">finally:</span><br><span class="line">    file.close()</span><br><span class="line"></span><br><span class="line"># 可使用with代替上面的写法,不需要自己管理资源</span><br><span class="line"></span><br><span class="line">with open(&quot;salaryfield.txt&quot;) as file:</span><br><span class="line">        for line in file.readlines():</span><br></pre></td></tr></table></figure>

<h1 id="编码规范包"><a href="#编码规范包" class="headerlink" title="编码规范包"></a>编码规范包</h1><p>python提供了一个编码规范的工具包，可以自行安装</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">sudo pip3 install autopep8</span><br></pre></td></tr></table></figure>
<p>安装完后可以配置pycharm添加到其扩展工具里，就可以在代码中右键使用了。配置方式这里就不写了。</p>
<h1 id="面向对象编程"><a href="#面向对象编程" class="headerlink" title="面向对象编程"></a>面向对象编程</h1><p>class 关键字可以定义一个类,python中定义的类同样可以实现继承、封装、多态的特性</p>
<h2 id="类的使用示例"><a href="#类的使用示例" class="headerlink" title="类的使用示例"></a>类的使用示例</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"># 迭代类</span><br><span class="line"></span><br><span class="line">class ProjectIteration():  # 定义一个类</span><br><span class="line">    def __init__(self, name, code):</span><br><span class="line">        self.__name &#x3D; name  # 迭代名称 __开头表示私有属性，不可修改</span><br><span class="line">        self.code &#x3D; code  # 迭代编号</span><br><span class="line"></span><br><span class="line">    def printInfo(self):  # 定义一个方法</span><br><span class="line">        print(&#39;迭代名称：[%s] 迭代编号:[%s]&#39; % (self.__name, self.code))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class Bug():</span><br><span class="line">    &#39;定义bug类&#39;</span><br><span class="line">    pass  # pass 暂不实现</span><br><span class="line"></span><br><span class="line">currentPj &#x3D; ProjectIteration(&quot;智能薪酬&quot;, &quot;znxc001&quot;)  # 类的实例化</span><br><span class="line">currentPj.printInfo()</span><br><span class="line"></span><br><span class="line"># 类的继承</span><br><span class="line"># 父类</span><br><span class="line">class Animal():</span><br><span class="line">    def __init__(self,name,age&#x3D;0):</span><br><span class="line">        self.name &#x3D; name</span><br><span class="line">        self.age &#x3D; age</span><br><span class="line">    def run(self):</span><br><span class="line">        print(&quot;跑了一段距离&quot;)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"># 继承父类</span><br><span class="line">class Cat(Animal):</span><br><span class="line">    def __init__(self,name,age):</span><br><span class="line">        # self.name &#x3D; name</span><br><span class="line">        # self.age &#x3D; age</span><br><span class="line">        super().__init__(name,age)</span><br><span class="line">    def run(self):</span><br><span class="line">        print(&quot;小猫跑了一会&quot;) # 可以覆盖父类的方法</span><br><span class="line"></span><br><span class="line">tom &#x3D; Cat(&quot;tom&quot;,18)</span><br><span class="line">tom.run();</span><br><span class="line"></span><br><span class="line">print(&#39;tom 的类型是%s&#39;%type(tom))</span><br><span class="line">print(isinstance(tom,Animal))  # tom 是否是Animal的子类</span><br></pre></td></tr></table></figure>

<h2 id="自定义类支持with语法"><a href="#自定义类支持with语法" class="headerlink" title="自定义类支持with语法"></a>自定义类支持with语法</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">class TestWith():</span><br><span class="line">    def __enter__(self):</span><br><span class="line">        print(&#39;初始化...&#39;)</span><br><span class="line"></span><br><span class="line">    def __exit__(self, exc_type, exc_val, exc_tb):</span><br><span class="line">        if exc_tb &#x3D;&#x3D; None:</span><br><span class="line">            print(&#39;没有异常&#39;)</span><br><span class="line">        else:</span><br><span class="line">            print(&#39;产生异常%s&#39; % exc_val)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">with TestWith():</span><br><span class="line">    print(&#39;Test is running&#39;)</span><br><span class="line">    raise NameError(&quot;test&quot;)</span><br><span class="line"></span><br><span class="line">输出信息</span><br><span class="line">Traceback (most recent call last):</span><br><span class="line">  File &quot;&#x2F;home&#x2F;richey&#x2F;PycharmProjects&#x2F;pythonProject&#x2F;tutorial&#x2F;18TestWith.py&quot;, line 14, in &lt;module&gt;</span><br><span class="line">    raise NameError(&quot;test&quot;)</span><br><span class="line">NameError: test</span><br><span class="line">初始化...</span><br><span class="line">Test is running</span><br><span class="line">产生异常test</span><br></pre></td></tr></table></figure>

<h1 id="多线程编程"><a href="#多线程编程" class="headerlink" title="多线程编程"></a>多线程编程</h1><p>暂无</p>
<h1 id="标准库"><a href="#标准库" class="headerlink" title="标准库"></a>标准库</h1><p>python的一大优势就是各种库特别丰富</p>
<p>python官方提供的库称之为标准库,官方网站：<a href="https://docs.python.org/3/library/index.html" target="_blank" rel="noopener">https://docs.python.org/3/library/index.html</a></p>
<p>python标准库提供类丰富的内容，比如基础的文本操作、日期处理、网络、开发工具和调试工具等等</p>
<h2 id="正则库re"><a href="#正则库re" class="headerlink" title="正则库re"></a>正则库re</h2><p><a href="https://docs.python.org/3/library/re.html" target="_blank" rel="noopener">https://docs.python.org/3/library/re.html</a></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">import  re</span><br></pre></td></tr></table></figure>

<h2 id="日期与时间函数"><a href="#日期与时间函数" class="headerlink" title="日期与时间函数"></a>日期与时间函数</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">import time</span><br><span class="line">import datetime</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">print(time.time())</span><br><span class="line">print(time.localtime())</span><br><span class="line">print(time.strftime(&#39;%Y-%m-%d %H-%M-%S&#39;))</span><br><span class="line"></span><br><span class="line"># 1612010800.1010308</span><br><span class="line"># time.struct_time(tm_year&#x3D;2021, tm_mon&#x3D;1, tm_mday&#x3D;30, tm_hour&#x3D;20, tm_min&#x3D;46, tm_sec&#x3D;40, tm_wday&#x3D;5, tm_yday&#x3D;30, tm_isdst&#x3D;0)</span><br><span class="line"># 2021-01-30 20-46-40</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">print(datetime.datetime.now())</span><br><span class="line">newTime &#x3D; datetime.timedelta(minutes&#x3D;10) # 10分钟的偏移</span><br><span class="line">print(datetime.datetime.now() + newTime) # 10分钟后的时间</span><br><span class="line"></span><br><span class="line"># 2021-01-30 20:50:50.395245</span><br><span class="line"># 2021-01-30 21:00:50.395273</span><br><span class="line"></span><br><span class="line">newDay &#x3D; datetime.datetime(2021,1,30)</span><br><span class="line">print(newDay)</span><br><span class="line">datInterval &#x3D; datetime.timedelta(days&#x3D;10)</span><br><span class="line">print(newDay + datInterval)</span><br><span class="line"></span><br><span class="line"># 2021-01-30 00:00:00</span><br><span class="line"># 2021-02-09 00:00:00</span><br></pre></td></tr></table></figure>

<h2 id="数学相关"><a href="#数学相关" class="headerlink" title="数学相关"></a>数学相关</h2><h2 id="文本及目录操作"><a href="#文本及目录操作" class="headerlink" title="文本及目录操作"></a>文本及目录操作</h2><p><a href="https://docs.python.org/3/library/os.path.html" target="_blank" rel="noopener">https://docs.python.org/3/library/os.path.html</a></p>
<p><a href="https://docs.python.org/3/library/pathlib.html" target="_blank" rel="noopener">https://docs.python.org/3/library/pathlib.html</a></p>
<p>几个简单的demo，详细操作查询文档</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">import os</span><br><span class="line"></span><br><span class="line">import os</span><br><span class="line"></span><br><span class="line">print(os.path.abspath(&quot;.&quot;)) # 根据当前路径获取绝对路径</span><br><span class="line">print(os.path.abspath(&quot;..&quot;))</span><br><span class="line">print(os.path.exists(&quot;&#x2F;home&quot;))</span><br><span class="line">print(os.path.isfile(&quot;&#x2F;home&quot;))</span><br><span class="line">os.path.join(&quot;&#x2F;home&#x2F;richey&#x2F;&quot;,&quot;&#x2F;Download&#x2F;&quot;)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">from pathlib import Path</span><br><span class="line"></span><br><span class="line"># &gt;&gt;&gt; p &#x3D; Path(&#39;.&#39;)</span><br><span class="line"># &gt;&gt;&gt; [x for x in p.iterdir() if x.is_dir()]</span><br><span class="line"># [PosixPath(&#39;.hg&#39;), PosixPath(&#39;docs&#39;), PosixPath(&#39;dist&#39;),</span><br><span class="line">#  PosixPath(&#39;__pycache__&#39;), PosixPath(&#39;build&#39;)]</span><br></pre></td></tr></table></figure>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.png" alt="Richey Liu 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="Richey Liu 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    Richey Liu
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://10000hours.top/2021/01/30/python%E5%9F%BA%E7%A1%80/" title="python基础">http://10000hours.top/2021/01/30/python%E5%9F%BA%E7%A1%80/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Python/" rel="tag"># Python</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2021/01/01/CAP%E5%8E%9F%E7%90%86/" rel="next" title="CAP原理">
                <i class="fa fa-chevron-left"></i> CAP原理
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2021/02/19/Python%E5%BA%93-Pandas%E8%AF%B4%E6%98%8E/" rel="prev" title="Python库-Pandas说明">
                Python库-Pandas说明 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        
<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='//bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>

      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.jpg"
                alt="Richey Liu" />
            
              <p class="site-author-name" itemprop="name">Richey Liu</p>
              <p class="site-description motion-element" itemprop="description">花有重开时人无再少年</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">131</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">24</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">42</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/liubaolin" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-globe"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="brin.baolin@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-globe"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#数据类型和数据结构"><span class="nav-number">1.</span> <span class="nav-text">数据类型和数据结构</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#基础数据类型"><span class="nav-number">1.1.</span> <span class="nav-text">基础数据类型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#序列"><span class="nav-number">1.2.</span> <span class="nav-text">序列</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#字典-key-value"><span class="nav-number">1.3.</span> <span class="nav-text">字典(key-value)</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#流程控制"><span class="nav-number">2.</span> <span class="nav-text">流程控制</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#if"><span class="nav-number">2.1.</span> <span class="nav-text">if</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#for"><span class="nav-number">2.2.</span> <span class="nav-text">for</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#while"><span class="nav-number">2.3.</span> <span class="nav-text">while</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#文件操作"><span class="nav-number">3.</span> <span class="nav-text">文件操作</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#异常处理"><span class="nav-number">4.</span> <span class="nav-text">异常处理</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#函数"><span class="nav-number">5.</span> <span class="nav-text">函数</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#函数定义"><span class="nav-number">5.1.</span> <span class="nav-text">函数定义</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#函数变量作用域"><span class="nav-number">5.2.</span> <span class="nav-text">函数变量作用域</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#函数迭代器和生成器"><span class="nav-number">5.3.</span> <span class="nav-text">函数迭代器和生成器</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#lambda表达式"><span class="nav-number">5.4.</span> <span class="nav-text">lambda表达式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#内建函数"><span class="nav-number">5.5.</span> <span class="nav-text">内建函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#闭包"><span class="nav-number">5.6.</span> <span class="nav-text">闭包</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#装饰器"><span class="nav-number">5.7.</span> <span class="nav-text">装饰器</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#上下文管理器with"><span class="nav-number">5.8.</span> <span class="nav-text">上下文管理器with</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#编码规范包"><span class="nav-number">6.</span> <span class="nav-text">编码规范包</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#面向对象编程"><span class="nav-number">7.</span> <span class="nav-text">面向对象编程</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#类的使用示例"><span class="nav-number">7.1.</span> <span class="nav-text">类的使用示例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#自定义类支持with语法"><span class="nav-number">7.2.</span> <span class="nav-text">自定义类支持with语法</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#多线程编程"><span class="nav-number">8.</span> <span class="nav-text">多线程编程</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#标准库"><span class="nav-number">9.</span> <span class="nav-text">标准库</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#正则库re"><span class="nav-number">9.1.</span> <span class="nav-text">正则库re</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#日期与时间函数"><span class="nav-number">9.2.</span> <span class="nav-text">日期与时间函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#数学相关"><span class="nav-number">9.3.</span> <span class="nav-text">数学相关</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#文本及目录操作"><span class="nav-number">9.4.</span> <span class="nav-text">文本及目录操作</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 &mdash; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Richey Liu</span>

  
</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: 'espIarB7yj7vR1el85iiMLjb-gzGzoHsz',
        appKey: 'v35zFd1Yc4PX5KsGn2wHgrob',
        placeholder: '欢迎留言！',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("98BykxDu7C0UsRu0zaggGlMu-gzGzoHsz", "a21Q7nym42YYGdxdx2XxxQNM");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
